<template>
  <div>
    <!-- 新增或者编辑 -->
    <el-form
      :model="addForm"
      ref="addFormRef"
      label-position="top"
      :rules="rules"
    >
      <el-form-item prop="checkTitle" label="二维码标题">
        <el-input v-model="addForm.checkTitle" placeholder="请输入二维码标题" />
      </el-form-item>
      <el-form-item prop="checkLogo" label="二维码logo">
        <div>
          <!-- 预览图 -->
          <el-image
            v-if="addForm.checkLogo"
            :src="addForm.checkLogo"
            fit="cover"
            :preview-src-list="[addForm.checkLogo]"
            class="w-[100px] h-[100px] rounded"
          />

          <!-- 上传按钮 -->
          <el-upload
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <el-button type="primary">
              {{ addForm.checkLogo ? "重新上传" : "点击上传" }}
            </el-button>
          </el-upload>
        </div>

        <!-- 裁剪弹窗 -->
        <ImageCropper
          v-model="cropperVisible"
          :imgFile="imgFile"
          @cropped="handleCropped"
        />
      </el-form-item>
      <el-form-item prop="isDefault" label="是否默认">
        <el-radio-group v-model="addForm.isDefault">
          <el-radio-button label="是" :value="1" />
          <el-radio-button label="否" :value="2" />
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="remark" label="备注">
        <el-input v-model="addForm.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>

    <div class="fixed bottom-2 right-2">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        {{ loading ? "提交中..." : "提交" }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ImageCropper from "./ImageCropper.vue";
import { handleApiResponse } from "@/utils/request.js";
import {
  AddCheckQrCodeSetting,
  GetCheckOrderQrCodeInfo,
  UpdateCheckQrCodeSetting,
} from "../../../../../../wailsjs/go/api/CustomerApi";
import { UploadFile } from "../../../../../../wailsjs/go/api/FileSystem";

onMounted(() => {
  if (props.detailForm.id != 0) {
    getDetail();
  }
});

const emit = defineEmits(["handleBack"]);
const props = defineProps({
  detailForm: {
    type: Object,
    default: () => {},
  },
});

const addFormRef = ref(null);
const addForm = ref({
  checkTitle: "",
  checkLogo: "",
  isDefault: 1,
  remark: "",
});

const rules = ref({
  checkTitle: [{ required: true, message: "请输入二维码标题" }],
  checkLogo: [{ required: true, message: "请上传二维码logo" }],
  isDefault: [{ required: true, message: "请选择是否默认" }],
  remark: [{ required: false, message: "请输入备注" }],
});

const cropperVisible = ref(false);
const imgFile = ref(null);

// 图片上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = /^image\/(jpeg|png|jpg|gif)$/.test(file.type);
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过5MB!");
    return false;
  }

  imgFile.value = file;
  cropperVisible.value = true;

  return false; // 阻止默认上传
};

// 处理裁剪后的图片
const handleCropped = async (blob) => {
  try {
    // 将文件读取为 ArrayBuffer
    const arrayBuffer = await blob.arrayBuffer();

    // 将 ArrayBuffer 转换为 Uint8Array
    const uint8Array = new Uint8Array(arrayBuffer);

    // 关键步骤：将 Uint8Array 转换为普通数组
    const fileBytesArray = Array.from(uint8Array);

    // 调用上传API
    handleApiResponse(() => UploadFile(fileBytesArray)).then((res) => {
      if (res.code === 0) {
        addForm.value.checkLogo = res.data.path;
        // ElMessage.success("上传成功");
        imgFile.value = null;
      }
    });
    // const res = await UploadFile(uint8Array);
  } catch (err) {
    ElMessage.error("上传失败");
    console.error(err);
    imgFile.value = null; // 重置文件引用
  }
};

// 获取详情
async function getDetail() {
  handleApiResponse(() =>
    GetCheckOrderQrCodeInfo({ id: props.detailForm.id })
  ).then((res) => {
    if (res.code == 0) {
      addForm.value = res.data || {};
    }
  });
}

const handleCancel = (val = 0) => {
  addFormRef.value.resetFields();
  emit("handleBack", val);
};

const loading = ref(false);
const handleSubmit = () => {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    if (props.detailForm.id == 0) {
      handleApiResponse(() => AddCheckQrCodeSetting(addForm.value)).then(
        (res) => {
          if (res.code == 0) {
            ElMessage.success("新增成功");
            handleCancel(1);
          }
        }
      );
    } else {
      handleApiResponse(() => UpdateCheckQrCodeSetting(addForm.value)).then(
        (res) => {
          if (res.code == 0) {
            ElMessage.success("编辑成功");
            handleCancel(1);
          }
        }
      );
    }
  });
};
</script>

<style scoped lang="scss">
</style>